package cn.jobstart.common;

import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import com.itextpdf.tool.xml.XMLWorkerHelper;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @author sunke
 * @Date 2021/5/24 上午10:19
 * @description
 */


public class HtmlToPdf {


    public static void htmToPdf2(String fltPath, String fltName, String fontPath, String imgPath, Map<String, Object> dataMap, OutputStream outputStream, String waterStr) throws Exception {

        FreeMarkerUtil freeMarkerUtil = FreeMarkerUtil.getInstance("/");

        String content = freeMarkerUtil.geneFileStr(fltName, fltPath, dataMap);
        PdfUtils.htmlToPdf(content, fontPath, imgPath, outputStream);


        // htmToPdf(fltPath,fltName,fontPath,dataMap,outputStream,waterStr);


    }


    public static void htmToPdf(String fltPath, String fltName, String fontPath, Map<String, Object> dataMap, OutputStream outputStream, String waterStr) throws Exception {

        FreeMarkerUtil freeMarkerUtil = FreeMarkerUtil.getInstance("/");

        //生成html
        String tempHtml = fltPath + File.separator + IdGen.uuid() + ".html.tmp";
        OutputStream fileOutputStream = new FileOutputStream(new File(tempHtml));
        freeMarkerUtil.print(fltName, dataMap, fltPath, fileOutputStream);


        Document document = new Document(PageSize.A4.rotate());
        PdfWriter writer = PdfWriter.getInstance(document, outputStream);
        document.open();
        XMLWorkerFontProvider fontImp = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
        fontImp.register(fontPath);

        XMLWorkerHelper.getInstance().parseXHtml(writer, document,
                new FileInputStream(tempHtml), null, StandardCharsets.UTF_8, fontImp);

        document.close();

        FileUtil.deleteFile(tempHtml);


    }


    /**
     * @param fltPath
     * @param fltName
     * @param fontPath
     * @param dataMap
     * @param targetPath
     * @param targetName
     * @param waterStr
     * @throws Exception
     */
    public static void htmToPdf(String fltPath, String fltName, String fontPath, Map<String, Object> dataMap, String targetPath, String targetName, String waterStr) throws Exception {

        htmToPdf(fltPath, fltName, fontPath, dataMap, new FileOutputStream(targetPath + File.separator + targetName), waterStr);

    }


}
